package com.baizhi.interceptors;
/**
 * 创建拦截器类
 */

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baizhi.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component //将对象交给spring容器管理
public class JwtTokenInterceptor implements HandlerInterceptor {//需要继承HandlerInterceptor拦截器类

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //token放在http请求头中，所以得从请求头中获取
        String token = request.getHeader("token");
        Map<String,Object> map = new HashMap<>();
        try {
            //通过自定义的类验证token
            JWTUtils.verify(token);
            //验证成功返回true，表示放行
            return true;
        } catch (TokenExpiredException e) {
            map.put("state", false);
            map.put("msg", "Token已经过期!!!");
        } catch (SignatureVerificationException e){
            map.put("state", false);
            map.put("msg", "签名错误!!!");
        } catch (AlgorithmMismatchException e){
            map.put("state", false);
            map.put("msg", "加密算法不匹配!!!");
        } catch (InvalidClaimException e){
            map.put("state", false);
            map.put("msg", "失效的payload异常");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "无效token~~");
        }
        //将map转换成json格式
        String json = new ObjectMapper().writeValueAsString(map);
        //指定响应的格式json和字符集utf8
        response.setContentType("application/json;charset=UTF-8");
        //响应json
        response.getWriter().println(json);
        return false;
    }
}
